<?php

namespace api\modules\backend\controllers;

use Yii;
use yii\filters\auth\QueryParamAuth;
use common\commands\Common;
use api\modules\backend\models\LoginForm;
use api\modules\backend\models\Role;

/**
 * User Controller API
 *
 * @author Fong <xiaofeng.zhang@suppernovachina.com>
 */
class UserController extends ControllerBase
{
    public $modelClass = 'api\modules\backend\models\Role';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className(),
            'optional' => [
                'login'
            ],
        ];
        $behaviors['authenticator']['except'] = ['options'];

        return $behaviors;
    }

    public function actionIndex()
    {
        $this->success();
    }

    /**
     * 登陆
     */
    public function actionLogin()
    {
        $model = new LoginForm();
        $post = Yii::$app->request->post();

        if (!isset($post['account']) || !isset($post['account'])) {
            $this->response(Common::getPackedResponse(MISSING_PARAMS, 'MISSING_PARAMS'));
        }

        $roleData = Role::findByAccount($post['account']);

        if (empty($roleData)) {
            $this->response(Common::getPackedResponse(USER_NOT_EXISTED, 'USER_NOT_EXISTED'));
        }

        $model->setAttributes(Yii::$app->request->post());

        if ($role = $model->login()) {
            if ($role instanceof role) {//判断是否是实例
                $data = array('token' => $role->access_token);

                $this->success($data);
            } else {
                $this->response(Common::getPackedResponse(USER_NOT_EXISTED, 'USER_NOT_EXISTED'));
            }
        } else {
            $this->response(Common::getPackedResponse(WRONG_PASSWORD, 'WRONG_PASSWORD'));
        }
    }
}